package org.idea.qiyu.framework.rpc.dubbo.router.starter.filter;

import com.alibaba.fastjson.JSON;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.idea.qiyu.common.constants.RequestConstants;
import org.idea.qiyu.common.context.QiyuRequestContext;
import org.idea.qiyu.common.context.QiyuCommonRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author linhao
 * @Date created in 10:54 下午 2021/7/31
 */
@Activate(group = {CommonConstants.CONSUMER}, order = -100000)
public class ConsumerContextFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerContextFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            Object object = QiyuRequestContext.get(RequestConstants.QIYU_BASE_REQUEST);
            if (null != object) {
                QiyuCommonRequest qiyuCommonRequest = (QiyuCommonRequest) object;
                String qiyuCommonRequestJson = JSON.toJSONString(qiyuCommonRequest);
                invocation.getAttachments().put(String.valueOf(RequestConstants.QIYU_BASE_REQUEST), qiyuCommonRequestJson);
                String headTraceId = qiyuCommonRequest.getTraceIdList().get(0);
                if (!StringUtils.isEmpty(headTraceId)) {
                    qiyuCommonRequest.setHeadTraceId(headTraceId);
                }
                System.out.println("consumer context filter 记录：" + qiyuCommonRequest);
                //日志上报功能
                try {
                    org.idea.qiyu.common.dto.AgentCollectorDataDTO agentCollectorDataDTO = new org.idea.qiyu.common.dto.AgentCollectorDataDTO();
                    agentCollectorDataDTO.setReportType((short) 1);
                    agentCollectorDataDTO.setHeadTraceId(headTraceId);
                    //todo暂时这么设计
                    Map<String,List<String>> itemMap = new HashMap<>();
                    itemMap.put(headTraceId,qiyuCommonRequest.getTraceIdList());
                    agentCollectorDataDTO.getTraceIdMap().add(itemMap);
                    agentCollectorDataDTO.setJson(qiyuCommonRequestJson);
                    agentCollectorDataDTO.setTimestamp(System.currentTimeMillis());
                    org.idea.qiyu.common.utils.ApmAgentUtil.doReport(agentCollectorDataDTO);
                    System.out.println("[consumer]日志上报,agentCollectorDataDTO is " + agentCollectorDataDTO);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            LOGGER.error("ConsumerContextFilter e is ", e);
        }
        return invoker.invoke(invocation);
    }
}
